package cn.kgc.vue.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Template;
import cn.kgc.vue.mapper.TemplateMapper;
import cn.kgc.vue.service.TemplateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
* @author mengshun
* @description 针对表【sys_template】的数据库操作Service实现
* @createDate 2023-12-15 13:44:22
*/
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService{


    @Override
    public ResponseResult getTemplateList(QueryCondition<Template> queryCondition) {

        Page<Template> templatePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        String fileName = queryCondition.getQuery().getFileName();
        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.eq(StringUtils.isNotEmpty(fileName),Template::getFileName,fileName);

        baseMapper.selectPage(templatePage,lambda);

        HashMap<String, Object> result = new HashMap<>();
        result.put("total",templatePage.getTotal());
        result.put("pageData",templatePage.getRecords());

        return ResponseResult.success().data(result);
    }

    @Override
    public ResponseResult uploadTemplate(MultipartFile file) {

        if ( file.isEmpty()){
            return  ResponseResult.fail().message("请选择文件");
        }

        // 文件上传
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = org.springframework.util.StringUtils.getFilenameExtension(originalFilename);

        String uuid = IdUtil.simpleUUID();
        String lastName = uuid+"."+filenameExtension;
        double size = file.getSize()/1024;
        File fil = new File("D:/upload/" + lastName);

        try {
            file.transferTo(fil);
            HashMap<String, Object> result = new HashMap<>();
            result.put("uuidName",lastName);
            result.put("size",size);
            return  ResponseResult.success().data(result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}




